using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Bludz
{
    class LogServer : Singleton<LogServer>
    {
        private TextWriter logFile;
        private List<string> buffer;
        private int numLines;

        public LogServer()
        {
            numLines = 5;
            buffer = new List<string>();

            logFile = new StreamWriter("log.html");
            logFile.WriteLine("<html><table border = \"1\">");
            logFile.WriteLine("<tr><th>Object</th><th>Message</th></tr>");
            logFile.Flush();

            EventServer.get().register("render2d", render2d);
        }

        public void render2d(string cmd, object[] args)
        {
            int ystep = GameServer.get().screenh / 4 / numLines;
            for (int i = 0; i < numLines && i < buffer.Count; ++i)
            {
                Graphics.get().renderText(buffer[i], 
                    new Vector2(0f, (float)i * (float)ystep),
                    Color.White, "tahoma");
            }
        }

        public void log(string name, string s)
        {
            buffer.Add(String.Format("{0}: {1}", name, s));
            if (buffer.Count >= numLines)
                buffer.RemoveAt(0);

            logFile.WriteLine("<tr><td>" + name + "</td><td>" + s + "</td></tr>");
            logFile.Flush();
        }

        public override void log(string s)
        {
            log("none", s);
        }
    }
}
